package com.clay.appointment.utils;

import com.clay.appointment.common.exception.GlobalException;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;

/**
 * 日期工具类
 *
 * @author Yeung Wah
 * @since 2021/5/7
 */
public class DateUtils {

    private DateUtils() {
    }

    private final static String DATE_TIME_FORMAT = "yyyy-MM-dd HH:mm:ss";
    private final static String DATE_FORMAT = "yyyy-MM-dd";

    private final static DateTimeFormatter DATE_TIME_FORMATTER = DateTimeFormatter.ofPattern(DATE_TIME_FORMAT);
    private final static DateTimeFormatter DATE_FORMATTER = DateTimeFormatter.ofPattern(DATE_FORMAT);

    /**
     * 获取日期和时间
     *
     * @return 日期时间字符串
     */
    public static String getDateTime() {
        return LocalDateTime.now().format(DATE_TIME_FORMATTER);
    }

    /**
     * 获取日期
     *
     * @return 日期字符串
     */
    public static String getDate() {
        return LocalDate.now().format(DATE_FORMATTER);
    }

    /**
     * 根据 pattern 生成日期字符串
     *
     * @param pattern pattern
     * @return 日期字符串
     */
    public static String getDateByPattern(String pattern) {
        return new SimpleDateFormat(pattern).format(new Date());
    }

    /**
     * 根据 pattern 将字符串转化为日期
     *
     * @param date    日期字符串
     * @param pattern pattern
     * @return 日期
     */
    public static Date parseDate(String date, String pattern) {
        SimpleDateFormat format = new SimpleDateFormat(pattern);
        try {
            return format.parse(date);
        } catch (ParseException e) {
            GlobalException.throwOut("日期转换失败！");
        }

        return null;
    }
}